package com.li.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.li.domain.Dept;
import com.li.service.DeptService;
import com.li.utlis.DeptUtil;
import com.li.utlis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @RequestMapping("/listDept")
    public List<Dept> listDept(){
        return deptService.list(new QueryWrapper<Dept>().eq("del_flag",0));
    }

    @RequestMapping("/listDeptTree")
    public List<Dept> listDeptTree(){
        return DeptUtil.recursion(deptService.list());
    }

    @RequestMapping("/listQueryDept")
    public List<Dept> listQueryDept(String name){
        return deptService.listQueryDept(name);
    }

    @RequestMapping("/listQueryDeptTree")
    public List<Dept> listQueryDeptTree(Dept dept){
        return DeptUtil.recursion(deptService.listQueryDeptTree(dept));
    }

    @PostMapping("saveOrUpdateDept")
    public JSONObject saveOrUpdataDept(Dept dept){
        try {
            if (dept.getDeptId()==null){
                deptService.addDept(dept);
            }else{
                deptService.updateDept(dept);
            }
        }catch (Exception e){
            return R.getError(dept);
        }
        return R.getSuccess();
    }

    @RequestMapping("/editDept/{deptId}")
    public Dept editDept(@PathVariable("deptId") Integer deptId){
        return deptService.getById(deptId);
    }

    /**
     * 删除
     * @param deptId
     * @return
     */
    @GetMapping("/delDept/{deptId}")
    public JSONObject delDept(@PathVariable("deptId") Integer deptId){
        boolean flag = deptService.delDept(deptId);
        if (flag){
            return R.getSuccess();
        }else {
            return R.getError(deptId);
        }
    }
}
